package com.allwees.bs.c.common.auth.oauth.facebook;

import com.alibaba.fastjson.JSONObject;
import com.allwees.bs.c.common.auth.AuthHandler;
import com.allwees.bs.c.common.auth.AuthResult;
import com.allwees.bs.c.common.auth.constant.EAuthType;
import com.allwees.bs.c.common.auth.model.OAuthUserInfo;
import com.allwees.bs.c.common.auth.util.HttpUtil;
import com.allwees.bs.c.module.user.entity.UserEntity;
import com.allwees.bs.c.module.user.req.ThirdPartLoginReq;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

/**
 * FacebookAuthHandler  facebook认证处理器
 * Date: 2018/8/15
 * Time: 09:39
 *
 * @author tianye
 */
@Slf4j
@Component
@Lazy(false)
public class FacebookAuthHandler extends AuthHandler {
	@Value("${facebook.resource.userInfoUri}")
	protected String fbBaseUrl;

	@Override
	public EAuthType getAuthType() {
		return EAuthType.FACEBOOK;
	}

	@Override
	public AuthResult auth(ThirdPartLoginReq loginReq) {
		String url = String.format(fbBaseUrl, loginReq.getToken());
		log.info("facebook auth params：{}", url);
		JSONObject json = HttpUtil.get(String.format(fbBaseUrl, loginReq.getToken()));
		String id = json.getString("id");
		//facebook email可能为空
		String email = json.getString("email");
		String firstName = json.getString("first_name");
		String lastName = json.getString("last_name");
		String avatarUrl = json.getJSONObject("picture").getJSONObject("data").getString("url");
		OAuthUserInfo userInfo = new OAuthUserInfo(loginReq.getSourceType(), getAuthType(), loginReq.getShareCode(), id, email, firstName, lastName, avatarUrl);
		//首选email
		UserEntity user = null;
		boolean updated = false;
		if(StringUtils.isNotBlank(email)){
			user = userDao.findByEmail(email);
		}
		if(user == null){
			user = userDao.findByFacebookId(id);
		} else {
			if(StringUtils.isBlank(user.getFacebookId())){
				user.setFacebookId(id);
				updated = true;
			}
			updated = updated || super.completeUserInfo(user, email, firstName, lastName, avatarUrl);
		}
		return auth(user, userInfo, updated);
	}
}
